package com.fyzk.activity.user.redpacket;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class PersonDaoImpl {
    private String sortKey = "";// 联系人首字母

    public PersonDaoImpl() {

    }

    private static final String[] CONTACT_PROJECTION = new String[]{
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME
    };
    private static final String[] PHONE_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.LABEL,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };


    private Context context;

    /**
     * 得到手机通讯录联系人信息
     **/
    public List<Person> getPhoneContacts(final Context mContext) {
        this.context = mContext;
        final List<Person> personList = new ArrayList<Person>();


        ContentResolver resolver = context.getContentResolver();

        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);


        while (cursor.moveToNext()) {
            String phoneName = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            String hasPhone = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            String id = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            if (hasPhone.equalsIgnoreCase("1")) {
                hasPhone = "true";
            } else {
                hasPhone = "false";
            }
            int nameKey = cursor.getColumnIndex("sort_key");
            if (Boolean.parseBoolean(hasPhone)) {
                Cursor phones = resolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = " + id, null, null);
                // 如果有多个电话，默认使用第一个，如果想使用最后一个，使用while，如果想选中间的 ，这里就需要弹出来让用户选择了，待定。。。。。。。。。。
                while (phones.moveToNext()) {

                    String phoneNumber = phones
                            .getString(phones
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String cursorKey = cursor.getString(nameKey);
                    Person person = new Person();
                    person.setCursorKey(cursorKey);
                    person.setName(phoneName);
                    person.setPhone(phoneNumber);
                    person.setId(cursor.getPosition());
                    Log.d("aa", "getPhoneContacts: "+phoneNumber);
                    if (!personList.contains(person) && ContactPhone.isPhone(phoneNumber)) {
                        personList.add(person);
                    }
                }
                phones.close();
            }
        }

        return personList;
    }


    /**
     * 加入联系人列表
     *
     * @param personList
     * @param name
     * @param phone
     */
    private void addPersonList(List<Person> personList, String name,
                               String phone) {
        for (int j = 0; j < personList.size(); j++) {
            if (name.equals(personList.get(j).getName())) {
                break;
            } else if (j == personList.size() - 1) {
                addPhone(personList, phone, name);
            }
        }
    }

    private void addPhone(List<Person> personList, String phone, String name) {
        Person person = new Person();
        person.setName(name);
        person.setPhone(phone);
        personList.add(person);
    }

    // 获取当前手机号
    public String getLocalNumber(Context mContext) {
        TelephonyManager tManager = (TelephonyManager) mContext
                .getSystemService(mContext.TELEPHONY_SERVICE);
        return tManager.getLine1Number();
    }

    /**
     * 获取联系人姓名
     *
     * @param mContext
     * @param mNumber
     * @return
     */
    public String getPeople(Context mContext, String mNumber) {
        String name = null;
        String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};

        // 将自己添加到 msPeers 中
        Cursor cursor = mContext.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, // Which columns to return.
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + mNumber + "'", // WHERE
                // clause.
                null, // WHERE clause value substitution
                null); // Sort order.

        if (cursor == null) {
            return null;
        }
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);

            // 取得联系人名字
            int nameFieldColumnIndex = cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            name = cursor.getString(nameFieldColumnIndex);
        }
        return name;
    }

}
